/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2023-02-07 17:41:15
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-15 19:51:25
 */
const app = getApp()

import {
    showMsg
} from '../../../utils/config.js'

import {
    reqAlarmHandling,
    reqAlarmCloseLoop
} from '../../../request/api.js'

import {
    validateEmoji,
    validateSpecial
} from '../../../utils/validate.js'

Page({
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        alarmInfo: {}, //告警信息
        form: {
            alarmFactor: '', //因素
            feedback: '', //反馈内容
            pic: '', //照片
        },
        showFactor: false,
        factorList: [{
            id: 1,
            text: '火警',
        }, {
            id: 2,
            text: '误报',
        }, {
            id: 3,
            text: '测试',
        }, {
            id: 4,
            text: '其它',
        }, ],
        disabledBtn: false,
    },
    onLoad(e) {
        this.getAlarmInfo(e)
    },
    // 获取告警信息
    getAlarmInfo(e) {
        console.log(e);
        let info = JSON.parse(e.info)
        this.setData({
            alarmInfo: info
        })
    },
    // 弹出告警确认类型
    clickFactor() {
        this.setData({
            showFactor: true
        })
    },
    // 隐藏告警确认类型
    factorClose() {
        this.setData({
            showFactor: false
        })
    },
    // 确定告警确认类型
    factorConfirm(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "form.type": value.id,
            "form.alarmFactor": value.text,
            showFactor: false,
        })
    },
    // 获取输入的告警确认类型
    factorChange(e) {
        this.data.form.alarmFactor = validateEmoji(e.detail.value.replace(/\s+/g, ''))
        this.setData({
            "form.alarmFactor": this.data.form.alarmFactor
        })
    },
    // 获取反馈内容
    feedbackChange(e) {
        this.data.form.feedback = validateEmoji(e.detail.value.replace(/\s+/g, ''))
        this.setData({
            "form.feedback": this.data.form.feedback
        })
    },
    clearFeedback() {
        this.setData({
            'form.feedback': ''
        })
    },

    // ------------照片开始
    addImage() {
        this.uploadFileFun()
    },
    uploadFileFun(item) {
        let that = this
        wx.chooseImage({
            count: 1,
            success(res) {
                console.log(res);
                var PicNums = res.tempFiles.length;
                for (var inta = 0; inta < PicNums; inta++) {
                    var path = res.tempFiles[inta].path;
                    var formatImage = path.split(".")[(path.split(".")).length - 1];
                    console.log("图片格式" + formatImage)
                    // 判断格式
                    if (formatImage != "png" && formatImage != "jpg") {
                        showMsg("只能上传.png、.jpg格式")
                    }
                    // 判断大小
                    let size = res.tempFiles.every(item => { //限制上传图片大小为2M,所有图片少于2M才能上传  
                        return item.size <= 20000000 //return item.size <= 2000000
                    })
                    console.log(size);
                    if (!size) {
                        showMsg("图片大小不能超过20MB!")
                        return;
                    }
                }

                const tempFilePaths = res.tempFilePaths
                tempFilePaths.forEach(item => {
                    wx.uploadFile({
                        url: app.globalData.reqUrl + 'file/upload',
                        filePath: item,
                        name: 'file',
                        header: {
                            "Content-Type": "multipart/form-data"
                        },
                        formData: {
                            "token": app.globalData.token,
                            "file": item,
                        },
                        success: function (res) {
                            let data = JSON.parse(res.data)
                            console.log(data);
                            if (data.code == 20000) {
                                that.updateImageList(data.data.url, item)
                                return showMsg("上传成功")
                            } else {
                                return showMsg("上传失败")
                            }
                        },
                        fail: function (e) {
                            return showMsg("上传失败")
                        }
                    })
                })
            }
        })
    },
    // 上传成功后更新照片列表
    updateImageList(url, item) {
        this.setData({
            "form.pic": url
        })
    },

    // 点击照片  发生的操作：预览、编辑、删除
    imageClick(e) {
        let {
            item
        } = e.currentTarget.dataset
        console.log(item);
        let that = this
        wx.showActionSheet({
            itemList: ['预览图片', '更换图片', '删除图片'],
            success(res) {
                let {
                    tapIndex
                } = res
                if (tapIndex === 0) {
                    that.previewImageFun(item)
                } else if (tapIndex === 1) {
                    that.updateImageFun(item)
                } else {
                    that.delImageFUn(item)
                }
            },
            fail(res) {
                console.log(res.errMsg)
            }
        })
    },
    // 1、预览图片
    previewImageFun(item) {
        wx.previewImage({
            current: item, // 当前显示图片的http链接
            urls: [item]
        })
    },
    // 2、更换图片
    updateImageFun(item) {
        this.uploadFileFun(item)
    },
    // 3、删除图片
    delImageFUn(item) {
        this.setData({
            "form.pic": ''
        })
    },
    // ------------照片结束

    // 确定
    async confirm() {
        if (this.data.disabledBtn) return
        let {
            alarmFactor,
            feedback,
            pic,
        } = this.data.form
        if(alarmFactor=='') return showMsg('告警确认类型不能为空')
        let {
            id,
            imei,
            orgName,
            name,
            classMark,
            deviceType,
            spaceId,
            alarmType,
            createTime,
        } = this.data.alarmInfo
        let params = {
            id,
            imei,
            orgName,
            name,
            classMark,
            deviceType,
            spaceId,
            alarmType,
            createTime,
            alarmFactor,
            feedback,
            pic,
            orgId: app.globalData.orgId ==1?this.data.alarmInfo.orgId:app.globalData.orgId,
            userId: app.globalData.userId,
        }
        const res = await reqAlarmHandling(params)
        if (res.code != 20000) return showMsg(res.message)
        // 完结
        let params2 = {
            id,
            imei,
            orgName,
            name,
            classMark,
            deviceType,
            spaceId,
            alarmType,
            createTime,
            orgId: app.globalData.orgId ==1?this.data.alarmInfo.orgId:app.globalData.orgId,
            userId: app.globalData.userId
        }
        const res2 = await reqAlarmCloseLoop(params2)
        if (res2.code != 20000) return showMsg(res2.message)

        showMsg("处理成功", "success")
        app.globalData.isBtnsAlarm=false;
        this.setData({
            disabledBtn: true
        })
        setTimeout(() => {
            wx.navigateBack({
                delta: 1,
            })
        }, 1000)
    }
})